from django.http import HttpResponse, JsonResponse
from django.shortcuts import render_to_response
from django.views.decorators.csrf import csrf_exempt
from django.db import connections
import requests
import logging
import traceback
import time
import re
from datetime import datetime
from dataflow.score_util import get_calc_app_score, get_calc_input_score

from decorate.decoration import timer

logger = logging.getLogger('bigdata.app.views')
g_retry_times = 3


@csrf_exempt
def hello_world(request, num):
    return HttpResponse("hello world {}".format(num))

# 待程杨给出imei的校验规则


def check_imei(imei):
    return True
    # if len(imei) > 10:
    #     return True
    # else:
    #     return False
    # regexp = re.match(r'[A-Za-z0-9]{14,}', imei)
    # if regexp is None:
    #     return False
    # return True


def check_timestamp(timestamp):
    # 因为时间戳的格式发生了变化所以修改这里的处理条件
    regexp = re.match(r'\d{8}', timestamp)
    if regexp is None:
        return False
    return True

# #业务方通知请求
# def calc_score(request):
#     start_time = time.time()
#     imei = request.GET.get('imei', '')
#     apply_time = request.GET.get('apply_time', '')
#     logger.info(imei + ', ' + apply_time)
#
#     if not (check_imei(imei) & check_timestamp(apply_time)):
#         return JsonResponse({'status': -1, 'mesg': 'arg value error'})
#
#     try:
#         timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
#         insert_sql = ''' insert into imei_score (imei, apply_time, score_app, score_input, is_expire, is_update, ctime) VALUES ('{0}', '{1}', '0', '0', 0, 0, '{2}')
#                       ON DUPLICATE KEY UPDATE score_app = VALUES(score_app), score_input = VALUES(score_input), is_expire = VALUES(is_expire), is_update = VALUES(is_update) '''.format(
#             imei, apply_time, timestamp)
#         db_imei = connections['imei']
#         cursor_imei = db_imei.cursor()
#         cursor_imei.execute(insert_sql)
#     except:
#         logger.error(imei + ', ' + apply_time + ', ' + traceback.format_exc())
#         return JsonResponse({'status': -1, 'mesg': 'database error'})
#     finally:
#         cursor_imei.close()
#     end_time = time.time()
#     interval_time = (end_time - start_time) * 1000
#     logger.info('interval_time ' + str(int(interval_time)))
#     return JsonResponse({'status': 0, 'mesg': 'success'})


# 直接利用http方式获取分数
@timer
def get_score_http(request):
    """
    author: chenjiannan
    :param request:
    :param output_flag: 对输出值进行一定控制，flag = app返回score_app, flag = input返回score_input, flag = 2返回两个值
    :return:
    """
    flag = request.GET.get('flag', '')
    imei = request.GET.get('imei', '')
    startDate = request.GET.get('startDate', '')
    endDate = request.GET.get('endDate', '')
    logging.info(','.join([flag, imei, startDate, endDate]))

    if not (check_imei(imei) and check_timestamp(
            startDate) and check_timestamp(endDate)):
        return JsonResponse({'status': -1, 'mesg': 'arg value error'})

    score_app, score_input = 1000, 1000
    # 按输出情况进行分类
    if flag == 'app':  # 返回score_app
        score_app = get_calc_app_score(
            imei, startDate, endDate)
        if score_app is not None:
            logging.info('calc score_app now ' + str(imei) + ' ' +
                         str(startDate) + ' ' + str(endDate) + ' ' + str(score_app))
        return JsonResponse(
            {'status': 0, 'mesg': 'success', 'data': {'score_app': score_app}})
    elif flag == 'input':  # 返回score_input
        score_input = get_calc_input_score(
            imei, startDate, endDate)
        if score_input is not None:
            logging.info('calc score_input now ' + str(imei) + ' ' +
                         str(startDate) + ' ' + str(endDate) + ' ' + str(score_input))
        return JsonResponse(
            {'status': 0, 'mesg': 'success', 'data': {'score_input': score_input}})
    else:
        score_app = get_calc_input_score(
            imei, startDate, endDate)
        score_input = get_calc_input_score(
            imei, startDate, endDate)
        if score_app is not None and score_input is not None:  # 数据没有问题
            logging.info('calc now ' + str(imei) + ' ' + str(startDate) + ' ' + str(endDate) +
                         ' ' + str(score_app) + ' ' + str(score_input))
        return JsonResponse({'status': 0, 'mesg': 'success', 'data': {
                            'score_app': score_app, 'score_input': score_input}})


# # 获取分数
# def get_score(request):
#     start_time = time.time()
#     imei = request.GET.get('imei', '')
#     apply_time = request.GET.get('apply_time', '')
#     logger.info(imei + ', ' + apply_time)
#
#     if imei == '' or apply_time == '':
#         return JsonResponse({'status': -1, 'mesg': 'arg value error'})
#
#     score_app = 1000  # 默认是0，try语句中抛出异常时用该值
#     score_input = 1000
#     try:
#         db_imei = connections['imei']
#         cursor_imei = db_imei.cursor()
#         cursor_imei.execute(
#             """ SELECT id, score_app, score_input, is_update FROM imei_score WHERE imei='{0}' AND apply_time = '{1}'  """.format(
#                 imei, apply_time))
#         select_data = cursor_imei.fetchone()
#
#         if select_data is not None:
#             _id = select_data[0]
#             score_app = select_data[1]
#             score_input = select_data[2]
#             is_update = select_data[3]
#             if is_update == 1:#score已经更新，直接获取返回
#                 logger.info('already exist table ' + ' ' + str(imei) + ' ' + str(apply_time) + ' ' + str(score_app) + ' ' + str(score_input))
#                 cursor_imei.execute(''' UPDATE imei_score set is_expire = 1 WHERE id = {0} '''.format(_id))
#             else:
#                 score_app, score_input = get_calc_score(imei, apply_time, calc_flag=True)
#                 if score_app is not None and score_input is not None:
#                     logger.info('calc now ' + str(imei) + ' ' + str(apply_time) + ' ' + str(score_app) + ' ' + str(score_input))
#                     cursor_imei.execute(
#                         "update imei_score set score_app='%s', score_input='%s', is_update=1, is_expire = 1 WHERE imei = '%s' AND apply_time=%s " % (
#                             score_app, score_input, imei, apply_time))
#         else:
#             return JsonResponse({'status': -1, 'mesg': 'imei is not exist'})
#
#     except:
#         logger.error(imei + ', ' + apply_time + ', ' + traceback.format_exc())
#         return JsonResponse({'status': -1, 'mesg': 'database error'})
#     finally:
#         cursor_imei.close()
#
#     end_time = time.time()
#     interval_time = (end_time - start_time) * 1000
#     logger.info('interval_time ' + str(int(interval_time)))
#
# return JsonResponse({'status': 0, 'mesg': 'success', 'data':
# {'score_app' : score_app, 'score_input' : score_input}})
